/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.trandio.manager;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import java.io.*;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.trandio.dao.*;
import org.trandio.model.*;

/**
 *
 * @author root
 */
public class AdministrarPrestador extends HttpServlet {

    PrestadorVO prestadorVO;
    PrestadorInterface prestadorInterface;
    private static final int DEFAULT_MAX_POST_SIZE = 1024 * 1024;  // 1 Meg
    private static final String DESTINO_DIRECTORIO = "/opt/rips/";
    private ConfigInterface configInterface;
    private ConfigVO configVO;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        configInterface = new ConfigDAO();
        prestadorInterface = new PrestadorDAO();
        HttpSession session = request.getSession(true);
        int idPrestador = (Integer) session.getAttribute("idepresed");
        try {
            configVO = configInterface.traerConfig(idPrestador);
        } catch (SQLException ex) {
            Logger.getLogger(GenerarRips.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(GenerarRips.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            try {
                prestadorVO = new PrestadorVO();
                MultipartRequest multipartRequest = new MultipartRequest(request, "/tmp/", 1048576, new DefaultFileRenamePolicy());

                if (multipartRequest.getParameter("op").equals("nuevo_prestador")) {
                    String cod = multipartRequest.getParameter("codigo");
                    String soc = multipartRequest.getParameter("razonsocial");
                    int tip = Integer.parseInt(multipartRequest.getParameter("idtipoiden"));
                    int num = Integer.parseInt(multipartRequest.getParameter("numeroidentificacion"));
                    int nit = Integer.parseInt(multipartRequest.getParameter("nit"));
                    int div = Integer.parseInt(multipartRequest.getParameter("digitoverificacion"));
                    int niv = Integer.parseInt(multipartRequest.getParameter("nivel"));
                    String coh = multipartRequest.getParameter("codhabilitacion");
                    int dep = Integer.parseInt(multipartRequest.getParameter("id_depto"));
                    int mun = Integer.parseInt(multipartRequest.getParameter("id_mupio"));
                    String dir = multipartRequest.getParameter("direccion");
                    String tel = multipartRequest.getParameter("telefono");
                    String ema = multipartRequest.getParameter("email");
                    String adjunto = "";
                     String newFileName = "";
                    if (multipartRequest.getFile("filelogo") != null) {
                        adjunto = multipartRequest.getFile("filelogo").toString().substring(5, multipartRequest.getFile("filelogo").toString().length());
                    
                    
                     File tmpFile = multipartRequest.getFile("filelogo");

                    //String ruta = configVO.getRutalogo() ;

                    String ruta = getServletConfig().getServletContext().getRealPath("/WEB-INF/classes/imagenes");

                    File dire = new File(ruta);
                    dire.mkdir();

                    File dirToMove = new File(ruta);

                    newFileName =  tmpFile.getName().replaceAll(" ", "")+String.valueOf(idPrestador);

                    File fileToMove = new File(dirToMove, newFileName);
                    tmpFile.renameTo(fileToMove);

                    FileInputStream fis = new FileInputStream(fileToMove);

                    tmpFile.delete();
     
                        
                    
                    }

                    
                    prestadorVO.setCodigo(cod);
                    prestadorVO.setRazonSocial(soc);
                    prestadorVO.setIdTipoIdentificacion(tip);
                    prestadorVO.setNumeroIdentificacion(num);
                    prestadorVO.setNit(nit);
                    prestadorVO.setDigitoVerificacion(div);
                    prestadorVO.setNivel(niv);
                    prestadorVO.setCodigoHabilitacion(coh);
                    prestadorVO.setIdDepartamento(dep);
                    prestadorVO.setIdMunicipio(mun);
                    prestadorVO.setDireccion(dir);
                    prestadorVO.setTelefono(tel);
                    prestadorVO.setEmail(ema);
                    prestadorVO.setLogo(newFileName);

                    prestadorInterface.guardarPrestador(prestadorVO);

                    out.println(request.getParameter("op"));
                } else if (multipartRequest.getParameter("op").equals("editar_prestador")) {
                   
                    int id = Integer.parseInt(multipartRequest.getParameter("id"));
                    String cod = multipartRequest.getParameter("codigo");
                    String soc = multipartRequest.getParameter("razonsocial");
                    int tip = Integer.parseInt(multipartRequest.getParameter("idtipoiden"));
                    int num = Integer.parseInt(multipartRequest.getParameter("numeroidentificacion"));
                    int nit = Integer.parseInt(multipartRequest.getParameter("nit"));
                    int div = Integer.parseInt(multipartRequest.getParameter("digitoverificacion"));
                    int niv = Integer.parseInt(multipartRequest.getParameter("nivel"));
                    String coh = multipartRequest.getParameter("codhabilitacion");
                    int dep = Integer.parseInt(multipartRequest.getParameter("id_depto"));
                    int mun = Integer.parseInt(multipartRequest.getParameter("id_mupio"));
                    String dir = multipartRequest.getParameter("direccion");
                    String tel = multipartRequest.getParameter("telefono");
                    String ema = multipartRequest.getParameter("email");
                    String adjunto = "";
                    String newFileName = "";

                    if (multipartRequest.getFile("filelogo") != null) {
                        adjunto = multipartRequest.getFile("filelogo").toString().substring(5, multipartRequest.getFile("filelogo").toString().length());
                        String nombreLogo = (String) session.getAttribute("nombrelogo");
                        String nombreLogoCom = getServletConfig().getServletContext().getRealPath("/WEB-INF/classes/imagenes")+"/"+nombreLogo;
                        //buscar el logo y borrar para guarar el nuevo
                        File logoaux = new File(nombreLogoCom);
                        logoaux.delete();
                        
                        File tmpFile = multipartRequest.getFile("filelogo");
                        //String ruta = configVO.getRutalogo() ;
                        String ruta = getServletConfig().getServletContext().getRealPath("/WEB-INF/classes/imagenes");
                        File dire = new File(ruta);
                        dire.mkdir();
                        File dirToMove = new File(ruta);
                        newFileName =  tmpFile.getName().replaceAll(" ", "")+String.valueOf(idPrestador);
                        File fileToMove = new File(dirToMove, newFileName);
                        tmpFile.renameTo(fileToMove);
                        FileInputStream fis = new FileInputStream(fileToMove);
                        tmpFile.delete();

                    }
                    prestadorVO.setId(id);
                    prestadorVO.setCodigo(cod);
                    prestadorVO.setRazonSocial(soc);
                    prestadorVO.setIdTipoIdentificacion(tip);
                    prestadorVO.setNumeroIdentificacion(num);
                    prestadorVO.setNit(nit);
                    prestadorVO.setDigitoVerificacion(div);
                    prestadorVO.setNivel(niv);
                    prestadorVO.setCodigoHabilitacion(coh);
                    prestadorVO.setIdDepartamento(dep);
                    prestadorVO.setIdMunicipio(mun);
                    prestadorVO.setDireccion(dir);
                    prestadorVO.setTelefono(tel);
                    prestadorVO.setEmail(ema);
                    prestadorVO.setLogo(newFileName);
                    prestadorInterface.guardarPrestadorEdit(prestadorVO);
                    out.println(request.getParameter("op"));

                }

            } catch (SQLException ex) {
                Logger.getLogger(AdministrarSetServlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NamingException ex) {
                Logger.getLogger(AdministrarSetServlet.class.getName()).log(Level.SEVERE, null, ex);
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}